<?php
/**
 * Created by PhpStorm.
 * User: Guojunchen
 * Date: 2018/4/13
 * Time: 11:17
 */

namespace app\common\lib;

/**
 * 用户基础类库
 * Class User
 * @package app\common\lib
 */
class User {

    /**
     * 相关token生成
     * @param $user_info
     * id = 用户id
     */
    public static function encode_token($user_info, $type = 'access_token'){
        $ret = false;
        $last_login_time = time();
        $last_login_ip = request()->ip();
        if ($user_info && is_array($user_info) && $type){
            switch ($type){
                case 'access_token':
                    $ret = Encryption::encode($user_info['uid'].':'.$last_login_time.':'.$last_login_ip);
                    break;
            }
        }

        return $ret;
    }

    public static function decode_token($token, $type = 'access_token'){
        $ret = array();
        if ($token && $type){
            $str = Encryption::decode($token);
            if ($str){
                switch ($type){
                    case 'access_token':
                        list($ret['uid'], $ret['last_login_time'], $ret['last_login_ip']) = explode(':', $str);
                        break;
                }
            }
        }

        return $ret;
    }

    /**
     * 检测是否登录
     */
    public static function check_login(){
        $headers = request()->header();
        if (empty($headers['access-token'])){
            renderJson('未登录，请先登录', -10086);
        }
        $access_token = $headers['access-token'];
        $access_token = stripslashes($access_token);
        $access_token = str_replace(' ', '+', $access_token);
        $logined_info = self::decode_token($access_token, 'access_token');
        if (!$logined_info){
            renderJson('登录失败，请重新登录', -10086);
        }
        $uid = $logined_info['uid'];
        if ($uid){
            // 检查access_token是否最新
            $user_info = model('User')->field('access_token')->where(['uid'=>$uid])->find();
            if ($user_info['access_token'] && $user_info['access_token'] != $access_token){
                renderJson('您的帐号在另一台设备上登录', -10086);
            }
            return true;
        } else{
            renderJson('登录超时，请重新登录', -10086);
        }
    }
}